//
//  BaseQueue.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2020/11/25.
//  Copyright © 2020 wangws1990. All rights reserved.
//

//import UIKit
//import SQLite.Swift
import SwiftyJSON
import SQLite
private let tableName = "mortgage"
private let table = Table(tableName)
private let id                   = Expression<String>("primaryId")
//表模型数据
private let data                 = Expression<String?>("data")

class BaseQueue{
    init() {
        guard let db = dataBase.db else { return  }
        let run = table.create(ifNotExists: true, block: { (table) in
            //注意.autoincrement
            table.column(id,primaryKey: true)
            table.column(data)
        })
        guard let _ = try? db.run(run) else { return }
    }
    public func haveData(primaryId :String) -> Bool{
        guard let db = dataBase.db else { return false }
        let alice = table.filter(id == primaryId)
        guard let count = try? db.scalar(alice.count) else { return false }
        return count > 0 ? true : false
    }
    public func insertData(primaryId :String,content : String,completion:@escaping ((_ success : Bool) -> ())){
        guard let db = dataBase.db else { return completion(false) }
        let have = haveData(primaryId: primaryId)
        if !have{
            let insertdata = table.insert(id <- primaryId,data <- content)
            guard let _ = try? db.run(insertdata) else { return completion(false) }
            completion(true)
        }else{
            updateData(primaryId: primaryId, content: content, completion: completion)
        }
    }
    public func updateData(primaryId :String,content : String,completion:@escaping ((_ success : Bool) -> Void)){
        guard let db = dataBase.db else { return completion(false) }
        let have = haveData(primaryId: primaryId)
        if !have {
            insertData( primaryId: primaryId, content: content, completion: completion)
        }else{
            let run = table.filter(id == primaryId)
            let update = run.update(id <- primaryId,data <- content)
            guard let _ = try? db.run(update) else { return completion(false) }
            completion(true)
        }
    }
    public func deleteData(primaryId :String,completion:@escaping ((_ success : Bool) -> ())){
        guard let db = dataBase.db else { return completion(false) }
        let alice = table.filter(id == primaryId)
        guard let _ = try? db.run(alice.delete()) else { return completion(false) }
        completion(true)
    }
    public func searchData(primaryId :String,completion:@escaping ((_ datas : JSON) -> ())){
        guard let db = dataBase.db else { return completion(false) }
        let alice = table.filter(id == primaryId)
        guard let datas : AnySequence<Row> = try? db.prepare(alice) else {
            return completion("")
        }
        decodeData(listData: datas, completion: completion)
    }
    public func searchData(page : Int,size : Int = 20,completion:@escaping ((_ datas : JSON) ->())){
        guard let db = dataBase.db else { return completion(JSON()) }
        let order = table.order(id.asc).limit(size, offset: (page - 1) * size)

        guard let datas : AnySequence<Row> = try? db.prepare(order) else {
            return completion(JSON(""))
        }
        decodeData(listData: datas,completion: completion)
    }
    public func searchData(completion:@escaping ((_ datas : JSON) ->())){
        guard let db = dataBase.db else { return completion(JSON()) }
        guard let datas : AnySequence<Row> = try? db.prepare(table) else {
            return completion(JSON(""))
        }
        decodeData(listData: datas,completion: completion)
    }
    private  func decodeData(listData : AnySequence<Row>,completion:@escaping ((_ datas : JSON) ->Void)){
        DispatchQueue.global().async {
            var contentData : [JSON] = []
            listData.forEach { (objc) in
                if let json = try? objc.get(data) {
                    let json = JSON(parseJSON:json)
                    contentData.append(json)
                }
            }
            let json = JSON(contentData)
            DispatchQueue.main.async {
                completion(json)
            }
        }
    }
    public  func dropTable(_ name :String,completion:@escaping ((_ success : Bool) ->Void)){
        let exeStr = "drop table if exists \(name) "
        guard let db = dataBase.db else { return completion(false)}
        guard let _ = try? db.execute(exeStr) else { return completion(false) }
    }
}
